<?php

namespace app\api\controller;

use think\Db;

// 产品(classify 0 官方产品 1 自由产品)
// supply_price 官方产品才有供货价（只能帮主看的到 供应商才能修改。但是供应商修改的价格，并非是帮主能看到的，我们还需要在上面加我们的利润，自有产品没有供货价）
// retail_price 零售价格（所有人能看 帮主才能修改）
// 官方产品由product的retail_price作为建议零售价 suggest_price 建议售价（所有人能看 官方产品供应商才能修改 供应商在上传产品资料的时候需要输入 自有产品帮主才能修改）
// tag_price 吊牌价格（所有人能看 吊牌价是用来算折扣的 官方产品供应商才能修改 供应商在上传产品资料的时候需要输入 自有产品帮主才能修改）
// gang_price 帮会价格（供应商在上架产品的时候，需要设置一个帮会价，帮主可以往高改，不能往低改，成员帮主都能看到）
// 折扣（帮内）= 最低帮会价/吊牌价
// 折扣（分享出去或朋友圈）= 最低零售价/吊牌价
// 所有规格里吊牌价都一样
// 官方产品对应的gang_product里的每个规格sold_out都一样
class Product extends BaseController
{
    // 筛选条件
    public function getFilterData()
    {
        $brand_data = Db::name('brand')->field('id,name')->select();
        array_unshift($brand_data, ['name' => '全部品牌', 'id' => '0']);
        $type_data = Db::name('type')->field('id,name')->select();
        array_unshift($type_data, ['name' => '全部类别', 'id' => '0']);
        // 暂时不开放自有产品
        // $data = [['name' => '全部产品', 'data' => [['name' => '全部产品', 'id' => -1], ['name' => '官方产品', 'id' => 0], ['name' => '自有产品', 'id' => 1]]], ['name' => '全部类别', 'data' => $type_data], ['name' => '全部品牌', 'data' => $brand_data]];
        $data = [['name' => '全部类别', 'data' => $type_data], ['name' => '全部品牌', 'data' => $brand_data]];

        return success($data);
    }

    // 产品列表(sold_out 1卖光[下架] 0正常[上架])
    public function getProductList()
    {
        $user_info = session('user_info');
        $classify = input('post.classify', -1);
        $type = input('post.type', '');
        $brand = input('post.brand', '');
        $sold_out = input('post.sold_out', 0);
        if ($classify != -1) {
            $query['classify'] = intval($classify);
            if (1 == $classify) {
                $query['gang_id'] = $user_info['gang_id'];
            }
        }
        if ($type) {
            $query['type'] = $type;
        }
        if ($brand) {
            $query['brand'] = $brand;
        }
        $query_sold_out = $sold_out;
        if (0 != $sold_out) {
            $query['sold_out'] = ['neq', 0];
            $query_sold_out = ['neq', 0];
        } else {
            $query['sold_out'] = 0;
        }
        $data = Db::name('product')->where($query)->order('order', 1)->select();
        $result = [];
        foreach ($data as $key => $value) {
            //检查官方产品 在帮会里是否下架
            if (0 == $value['classify']) {
                // min 2种方法 1.排序取一个
                $gang_p_info = Db::name('gang_product')->where(['product_id' => $value['id'], 'gang_id' => $user_info['gang_id'], 'sold_out' => $query_sold_out])->order(['gang_price' => 1])->limit(1)->select();
                // 2.聚合函数
                // $r = Db::name('gang_product')->where(['product_id' => $value['id'], 'gang_id' => $user_info['gang_id'], 'sold_out' => $sold_out])->aggregate(['_id' => null, 'gang_price' => ['$min' => '$gang_price']]);
                if ($gang_p_info) {
                    unset($value['specifications']);
                    $value['price'] = round($gang_p_info[0]['gang_price'], 2);
                    $value['discount'] = round($gang_p_info[0]['gang_price'] / $value['tag_price'] * 10, 1);
                    $result[] = $value;
                }
                //检查自有产品是否下架
            } elseif (1 == $value['classify'] && $value['gang_id'] == $user_info['gang_id'] && $sold_out == $value['sold_out']) {
                $gang_price_arr = array_column($value['specifications'], 'gang_price');
                $gang_price = min($gang_price_arr);
                unset($value['specifications']);
                $value['price'] = round($gang_price, 2);
                $value['price'] = round($gang_price, 2);
                $value['discount'] = round($gang_price / $value['tag_price'] * 10, 1);
                unset($value['specifications']);
                $result[] = $value;
            }
        }
        $data = $result;

        return success($data);
    }

    // 获取产品详情（散客、其他帮会成员也是这个接口,需要传shop_id，散客看到的是retail_price tag_price）
    public function getDetail()
    {
        $user_info = session('user_info');
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        $shop_id = input('post.shop_id', '');
        if ($shop_id) {
            $shop_info = Db::name('shop')->where('id', $shop_id)->find();
            $gang_id = $shop_info['gang_id'];
        } else {
            $gang_id = $user_info['gang_id'];
        }
        if (!$gang_id) {
            return error('未找到该帮会');
        }

        $data = Db::name('product')->find($product_id);
        $data['gang_id'] = $gang_id;
        $query['product_id'] = $product_id;
        $order = ['level' => -1, 'ct' => -1];
        $evaluate = Db::name('evaluate')->where($query)->order($order)->find();
        if ($evaluate) {
            $evaluate['user_info'] = Db::name('user')->field('name,avatar')->find($evaluate['buyer']);
            $evaluate['ct'] = date('Y-m-d', $evaluate['ct']);
        }
        $data['evaluate'] = $evaluate;
        $data['evaluate_count'] = Db::name('evaluate')->where(['product_id' => $product_id])->count();
        // 段子总数
        $data['passage_count'] = Db::name('product_passage')->where(['product_id' => $product_id, 'gang_id' => $gang_id])->count();
        $data['passage_count'] += count($data['passage']);
        $role = 0;
        if ($user_info['gang_id'] == $gang_id) {
            $role = intval($user_info['gang_role']);
        }
        $gang_info = Db::name('gang')->find($gang_id);
        $gang_type = Db::name('gang_type')->find($gang_info['type_id']);

        $after_sale_intro = Db::name('product_after_sale_intro')->where('admin_id', $data['admin_id'])->find();
        $data['after_sale_is_setting'] = $after_sale_intro ? '已设置' : '未设置';
        $data['after_sale_intro'] = $after_sale_intro['info'];
        //官方产品单独查询帮会价格（自有产品自带帮会价）
        if (isset($data['classify']) && 0 == $data['classify'] && isset($data['specifications'])) {
            $gang_price = Db::name('gang_product')->where(['product_id' => $data['id'], 'gang_id' => $gang_id])->select();

            $min = 9999999999;
            foreach ($data['specifications'] as  $key => $item) {
                unset($data['specifications'][$key]['real_supply']);
                if ($role >= 5) {
                    $raise_price = round($gang_type['raise_price_list'][$data['brand']][$data['type']] / 100 + 1, 4);
                    $supply_price = round($raise_price * $data['specifications'][$key]['supply_price'], 2);
                    $data['specifications'][$key]['supply_price'] = $supply_price;
                }
                $data['specifications'][$key]['gang_price'] = round($item['gang_price'], 2);
                $data['specifications'][$key]['stock'] = intval($item['stock']);
                foreach ($gang_price as $value) {
                    if ($item['title'] == $value['specifications']) {
                        if ($role >= 2) {
                            $data['specifications'][$key]['gang_price'] = round($value['gang_price'], 2);
                            $data['specifications'][$key]['retail_price'] = round($value['retail_price'], 2);
                            $data['specifications'][$key]['fans_reward'] = round($value['fans_reward'], 2);
                        } else {
                            $data['specifications'][$key]['gang_price'] = round($value['retail_price'], 2);
                            $data['specifications'][$key]['retail_price'] = round($data['tag_price'], 2);
                            $data['specifications'][$key]['fans_reward'] = 0;
                        }
                        if ($min > $data['specifications'][$key]['gang_price']) {
                            $min = $data['specifications'][$key]['gang_price'];
                        }

                        $data['sold_out'] = $value['sold_out'];
                    }
                }
            }
            $data['discount'] = round($min / $data['tag_price'] * 10, 1);
        }

        return success($data);
    }

    // 下单专用 获取产品基本信息（散客也是这个接口,需要传gang_id，散客看到的是retail_price tag_price）
    public function getDetails()
    {
        $user_info = session('user_info');
        $product_ids = input('post.product_ids/a', '');
        if (!is_array($product_ids) || 0 == count($product_ids)) {
            return error('参数错误：错误的product_ids');
        }
        $gang_id = input('post.gang_id', '');
        $shop_id = input('post.shop_id', '');
        if (!$gang_id && $shop_id) {
            $shop_info = Db::name('shop')->where('id', $shop_id)->find();
            $gang_id = $shop_info['gang_id'];
        }
        if (!$gang_id) {
            $gang_id = $user_info['gang_id'];
        }
        $result = [];
        foreach ($product_ids as  $product_id) {
            $row = [];
            $data = Db::name('product')->find($product_id);
            $query['product_id'] = $product_id;
            $order = ['level' => -1, 'ct' => -1];
            $role = 0;
            if ($user_info['gang_id'] == $gang_id) {
                $role = intval($user_info['gang_role']);
            }
            $row['id'] = $data['id'];
            $row['weight'] = $data['weight'];
            // $postage_info = Db::name('postage')->where(['admin_id' => $data['admin_id'], 'express_code' => 'SF'])->find();
            // $row['postage'] = $postage_info['table'];
            $row['pic'] = $data['pic'];
            $row['name'] = $data['name'];
            //官方产品单独查询帮会价格（自有产品自带帮会价）
            if (isset($data['classify']) && 0 == $data['classify'] && isset($data['specifications'])) {
                $gang_price = Db::name('gang_product')->where(['product_id' => $data['id'], 'gang_id' => $gang_id])->select();
                $row['specifications'] = [];
                foreach ($gang_price as $value) {
                    foreach ($data['specifications'] as  $key => $item) {
                        unset($data['specifications'][$key]['supply_price']);
                        unset($data['specifications'][$key]['real_supply']);
                        if ($item['title'] == $value['specifications']) {
                            $row['specifications'][$key]['title'] = $item['title'];
                            if (isset($value['gang_price'])) {
                                if ($role >= 2) {
                                    $row['specifications'][$key]['gang_price'] = round($value['gang_price'], 2);
                                } else {
                                    $row['specifications'][$key]['gang_price'] = round($value['retail_price'], 2);
                                }
                            }
                            if (isset($value['retail_price'])) {
                                if ($role >= 2) {
                                    $row['specifications'][$key]['retail_price'] = round($value['retail_price'], 2);
                                } else {
                                    $row['specifications'][$key]['retail_price'] = round($item['tag_price'], 2);
                                }
                            }
                            $row['specifications'][$key]['stock'] = intval($value['stock']);
                            $row['sold_out'] = $value['sold_out'];
                        }
                    }
                }
            }
            $result[] = $row;
        }

        return success($result);
    }

    // 朋友圈素材
    public function getMaterial()
    {
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        $data = Db::name('material')->where(['product_id' => $product_id])->select();

        return success($data);
    }

    // 便捷操作 修改价格（这个方法让帮主只能修改零售价格）
    public function editPrice()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        $data = Db::name('product')->find($product_id);
        if (!$data) {
            return error('未找到该产品');
        }
        $gang_info = Db::name('gang')->find($user_info['gang_id']);
        $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
        $specifications = input('post.specifications/a', []);
        foreach ($specifications as $key => $value) {
            $gang_price = Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id'], 'specifications' => $value['title']])->find();
            $retail_price = round($value['retail_price'], 2);
            $get_gang_price = round($value['gang_price'], 2);
            if ($retail_price <= 0) {
                return error('参数错误：错误的零售价格');
            }
            if ($retail_price <= $get_gang_price) {
                return error('零售价必须大于帮会价');
            }
            $flag = false;
            $current = [];
            foreach ($data['specifications'] as $k => $v) {
                if ($v['title'] == $value['title']) {
                    $flag = true;
                    $current = $v;
                    break;
                }
            }
            if (!$flag) {
                return error('参数错误：错误的规格');
            }

            if ($retail_price < $current['suggest_price']) {
                return error('零售价必须大于建议零售价');
            }

            $raise_price = round($gang_type['raise_price_list'][$data['brand']][$data['type']] / 100 + 1, 4);
            $supply_price = round($raise_price * $current['supply_price'], 2);

            if ($get_gang_price <= $supply_price) {
                return error('帮会价必须大于供货价');
            }
        }

        foreach ($specifications as $key => $value) {
            $retail_price = round($value['retail_price'], 2);
            $get_gang_price = round($value['gang_price'], 2);
            //存在修改 不存在添加
            Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id'], 'specifications' => $value['title']])->update(['retail_price' => $retail_price, 'gang_price' => $get_gang_price], ['upsert' => true]);
        }

        return success();
    }

    // 售后说明（自有产品的）
    public function getAfterSaleIntro()
    {
        $user_info = session('user_info');
        $product_id = input('post.product_id', '');

        $data = Db::name('product_after_sale_intro')->where(['gang_id' => $user_info['gang_id'], 'product_id' => $product_id])->find();

        return success($data);
    }

    // 获取产品设置
    public function getSettings()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $gang_info = Db::name('gang')->find($user_info['gang_id']);

        $data = ['putaway' => ['自动上架', '手动上架'], 'selected_putaway' => intval($gang_info['putaway']), 'show_settings' => ['展示全部产品', '紧展示CH版本产品'], 'select_show_settings' => intval($gang_info['show_settings'])];

        return success($data);
    }

    // 设置产品设置
    public function setSettings()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $putaway = intval(input('post.putaway', 0));
        $show_settings = intval(input('post.show_settings', 0));

        $data = Db::name('gang')->where('id', $user_info['gang_id'])->update(['putaway' => $putaway, 'show_settings' => $show_settings]);

        return success($data);
    }

    // 下架
    public function soldOut()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的id');
        }
        Db::name('product')->where(['id' => $product_id, 'sold_out' => 0, 'classify' => 1])->update(['sold_out' => 1]);
        $data = Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->update(['sold_out' => 1]);

        return success($data);
    }

    // 新增自有产品
    public function createProduct()
    {
        return error('暂未开放自有产品');
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $data = input('post.', '');
        if (!$data['brand'] || 24 != strlen($data['brand'])) {
            return error('参数错误：错误的品牌');
        }
        $brand = Db::name('brand')->find($data['brand']);
        if (!$brand) {
            return error('参数错误：错误的品牌id');
        }
        if (!$data['type'] || 24 != strlen($data['type'])) {
            return error('参数错误：错误的类型');
        }
        $type = Db::name('type')->find($data['type']);
        if (!$type) {
            return error('参数错误：错误的类型id');
        }
        if (!$data['version'] || !in_array($data['version'], ['CH', 'TW', 'SP'])) {
            return error('参数错误：错误的版本');
        }
        if (!$data['pics'] || !is_array($data['pics']) || count($data['pics']) < 1) {
            return error('至少传一张产品图');
        }
        if (!$data['specifications']) {
            return error('请填写产品规格！');
        }

        $new_data = [];
        $new_data['gang_id'] = $user_info['gang_id'];
        $new_data['type'] = $data['type'];
        $new_data['brand'] = $data['brand'];
        $new_data['model'] = subString(strval($data['model']), 20);
        $new_data['version'] = $data['version'];
        $new_data['pic'] = $data['pics'][0];
        $new_data['pics'] = $data['pics'];
        $new_data['classify'] = 1;
        $new_data['name'] = $brand['name'].$data['model'].$type['name'].$data['version'].'版'; //品牌+型号+类别+版本
        $tag_price = 0;
        foreach ($data['specifications'] as $key => $value) {
            if (!$value['title']) {
                return error('请填写产品规格的名称！');
            }
            $row = [];
            $row['title'] = strval($value['title']);
            $row['stock'] = intval($value['stock']);
            //自有产品 （帮会/零售 吊牌价放外层）
            $row['retail_price'] = round($value['retail_price'], 2);
            $row['gang_price'] = round($value['gang_price'], 2);
            $new_data['specifications'][] = $row;
            $tag_price = round($value['tag_price'], 2);
        }
        $new_data['tag_price'] = $tag_price;
        $newId = Db::name('product')->insert($new_data);
        //将此帮会下的没有product_id的段子、售后说明 附上新的id
        Db::name('product_passage')->where(['gang_id' => $user_info['gang_id'], 'product_id' => ''])->update(['product_id' => $newId]);
        Db::name('product_after_sale_intro')->where(['gang_id' => $user_info['gang_id'], 'product_id' => ''])->update(['product_id' => $newId]);

        return success($new_data['id']);
    }

    // 修改产品
    public function editProduct()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }

        $data = input('post.', '');
        $product_info = Db::name('product')->find($product_id);

        if (!$product_info) {
            return error('未找到该产品');
        }
        if (!$data['brand'] || 24 != strlen($data['brand'])) {
            return error('参数错误：错误的品牌');
        }
        $brand = Db::name('brand')->find($data['brand']);
        if (!$brand) {
            return error('参数错误：错误的品牌id');
        }
        if (!$data['type'] || 24 != strlen($data['type'])) {
            return error('参数错误：错误的类型');
        }
        $type = Db::name('type')->find($data['type']);
        if (!$type) {
            return error('参数错误：错误的类型id');
        }
        if (!$data['version'] || !in_array($data['version'], ['CH', 'TW', 'SP'])) {
            return error('参数错误：错误的版本');
        }
        if (!$data['pics'] || !is_array($data['pics']) || count($data['pics']) < 1) {
            return error('至少传一张产品图');
        }
        if (!$data['specifications']) {
            return error('请填写产品规格！');
        }

        $new_data = [];
        $new_data['type'] = $data['type'];
        $new_data['brand'] = $data['brand'];
        $new_data['model'] = subString(strval($data['model']), 20);
        $new_data['version'] = $data['version'];
        $new_data['pic'] = $data['pics'][0];
        $new_data['pics'] = $data['pics'];
        $new_data['name'] = $brand['name'].$data['model'].$type['name'].$data['version'].'版'; //品牌+型号+类别+版本
        if (0 != $product_info['classify']) {
            //自有产品 （帮会/零售 吊牌放外层）
            foreach ($data['specifications'] as $key => $value) {
                if (!$value['title']) {
                    return error('请填写产品规格的名称！');
                }
                $row = [];
                $row['title'] = strval($value['title']);
                $row['stock'] = intval($value['stock']);
                $row['retail_price'] = round($value['retail_price'], 2);
                $row['gang_price'] = round($value['gang_price'], 2);
                $new_data['specifications'][] = $row;
                $tag_price = round($value['tag_price'], 2);
            }
            $new_data['sold_out'] = 0;
            $new_data['tag_price'] = $tag_price;
            Db::name('product')->where('id', $product_id)->update($new_data);
        } else {
            // 官方产品 只能改帮会价格、零售价格
            $gang_price = [];
            foreach ($data['specifications'] as $key => $value) {
                if (!$value['title']) {
                    return error('请填写产品规格的名称！');
                }
                $row['specifications'] = strval($value['title']);
                $row['product_id'] = strval($product_id);
                $row['sold_out'] = 0; //修改即上架
                $gang_product_info = Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id'], 'specifications' => $value['title']])->find();
                if ($gang_product_info['fans_reward']) {
                    $row['fans_reward'] = round($gang_product_info['fans_reward'], 2);
                }
                $row['gang_id'] = strval($user_info['gang_id']);
                $row['gang_price'] = round($value['gang_price'], 2);
                $row['retail_price'] = round($value['retail_price'], 2);
                $gang_price[] = $row;
            }
            Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->delete();
            Db::name('gang_product')->insertAll($gang_price);
            Db::name('product')->where('id', $product_id)->update($new_data);
        }

        return success();
    }

    // 上架官方产品的列表
    public function putawayList()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $type = input('post.type', '');
        $brand = input('post.brand', '');
        $query['classify'] = 0;
        if ($type) {
            $query['type'] = $type;
        }
        if ($brand) {
            $query['brand'] = $brand;
        }
        $query['sold_out'] = 0;
        $data = Db::name('product')->field('id,name,pic,specifications,tag_price')->where($query)->select();
        $result = [];
        foreach ($data as $key => $value) {
            // 去除已经上架的
            $find = Db::name('gang_product')->where(['product_id' => $value['id'], 'gang_id' => $user_info['gang_id'], 'sold_out' => 0])->find();
            if ($find) {
                continue;
            }
            $min = 9999999999;
            foreach ($value['specifications'] as $k => $v) {
                if ($min > $v['suggest_price']) {
                    $min = round($v['suggest_price'], 2);
                }
            }
            unset($value['specifications']);
            $value['price'] = round($min, 2);
            $value['discount'] = round($min / $value['tag_price'] * 10, 1);
            $result[] = $value;
        }

        return success($result);
    }

    // 帮会里上架官方产品
    public function putaway()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }

        $data = input('post.', '');
        $product_info = Db::name('product')->find($product_id);

        if (!$product_info) {
            return error('未找到该产品');
        }

        if (0 == $product_info['classify']) {
            // 上架官方产品 只能改帮会价格、零售价格
            $gang_price = [];
            foreach ($data['specifications'] as $key => $value) {
                if (!$value['title']) {
                    return error('请填写产品规格的名称！');
                }
                $current = [];
                foreach ($product_info['specifications'] as $k => $v) {
                    if ($value['title'] == $v['title']) {
                        $current = $v;
                        break;
                    }
                }
                $row['specifications'] = strval($value['title']);
                $row['product_id'] = strval($product_id);
                $row['sold_out'] = 0;
                $row['gang_id'] = strval($user_info['gang_id']);
                $row['gang_price'] = round($value['gang_price'], 2);
                $row['retail_price'] = round($value['retail_price'], 2);
                if ($row['gang_price'] < $current['supply_price']) {
                    return error('帮会价必须大于供货价');
                }
                if ($row['retail_price'] < $row['gang_price']) {
                    return error('零售价必须大于帮会价');
                }
                $gang_price[] = $row;
            }

            Db::name('gang_product')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->delete();
            Db::name('gang_product')->insertAll($gang_price);

            return success('上架成功');
        }

        return error('该产品不是官方产品');
    }

    // 新增、修改售后说明（自有产品的）
    public function editProductAfterSale()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $product_id = input('post.product_id', '');
        $content = input('post.content', '');
        if (!$content) {
            return error('请填写内容');
        }

        //存在修改 不存在添加
        $gang_price = Db::name('product_after_sale_intro')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->update(['content' => $content], ['upsert' => true]);

        return success();
    }

    // 获取全部海报图（产品图加自己上传）加上产品信息及段子
    public function getPosters()
    {
        $user_info = session('user_info');
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }

        $upload_pics = Db::name('upload')->where('user_id', $user_info['id'])->select();
        $data['imgs'] = [];
        foreach ($upload_pics as $key => $value) {
            $data['imgs'][] = $value['img_url'];
        }
        $product_info = Db::name('product')->field('id,name,pics,passage')->find($product_id);
        if ($product_info['pics']) {
            $data['imgs'] = array_merge($data['imgs'], $product_info['pics']);
        }
        $data['name'] = $product_info['name'];

        $product_passage = Db::name('product_passage')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->select();
        array_unshift($product_passage, ['content' => $product_info['passage']]);
        $data['product_passage'] = $product_passage;

        return success($data);
    }

    // 获取段子
    public function getPassage()
    {
        $user_info = session('user_info');
        $product_id = input('post.product_id', '');
        $product_info = Db::name('product')->field('passage')->find($product_id);
        $product_passage = Db::name('product_passage')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->select();
        array_unshift($product_passage, ['content' => $product_info['passage']]);

        return success($product_passage);
    }

    // 新增、修改段子
    public function editPassage()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $passage = input('post.passage/a', '');
        $product_id = input('post.product_id', '');
        $list = [];
        foreach ($passage as $key => $value) {
            if (!$value['content']) {
                return error('请填写段子内容');
            }
            $row = ['product_id' => $product_id, 'gang_id' => $user_info['gang_id'], 'content' => $value['content']];
            $list[] = $row;
        }

        Db::name('product_passage')->where(['product_id' => $product_id, 'gang_id' => $user_info['gang_id']])->delete();
        Db::name('product_passage')->insertAll($list);

        return success($data);
    }

    // 删除段子
    public function deletePassage()
    {
        $user_info = session('user_info');
        if (5 != intval($user_info['gang_role'])) {
            return error('你的权限不够');
        }
        $passage_id = input('post.passage_id', '');
        if (!$passage_id || 24 != strlen($passage_id)) {
            return error('参数错误：错误的passage_id');
        }
        $data = Db::name('product_passage')->delete($passage_id);

        return success($data);
    }

    // 查看商品的评价列表
    public function getEvaluateList()
    {
        $product_id = input('post.product_id', '');
        if (!$product_id || 24 != strlen($product_id)) {
            return error('参数错误：错误的product_id');
        }
        // tags -1全部 0带图 1好评 2差评
        $tags = input('post.tags', -1);
        if ($tags != -1) {
            if (0 == $tags) {
                $query['pics'] = ['neq', null];
            } elseif (1 == $tags) {
                $query['score'] = ['gt', 3];
            } elseif (2 == $tags) {
                $query['score'] = ['lt', 2];
            }
        }
        $query['product_id'] = $product_id;
        $limit = input('post.limit', 10);
        $page = input('post.page', 1);
        $order = ['ct' => -1];
        $data = Db::name('evaluate')->where($query)->order($order)->limit($limit)->page($page)->select();
        foreach ($data as $key => $value) {
            $data[$key]['ct'] = date('Y-m-d', $value['ct']);
            $buyer = Db::name('user')->field('id,name,avatar')->find($value['buyer']);
            $data[$key]['buyer'] = $buyer;
        }

        return success(['data' => $data, 'is_over' => count($data) < $limit]);
    }

    // 获取评价前的基本信息
    public function getEvaluateInfo()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $order_info = Db::name('order')->find($order_id);
        if (!$order_info) {
            return error('未找到该订单');
        }
        $user_id = $order_info['seller'];
        $product_id = input('post.product_id', '');
        if (!$product_id && count($order_info['product']) > 1) {
            return error('参数错误：错误的product_id');
        }
        if (!$product_id && 1 == count($order_info['product'])) {
            $product_id = $order_info['product'][0]['product_id'];
        } else {
            $flag = false;
            foreach ($order_info['product'] as $key => $value) {
                if ($product_id == $value['product_id']) {
                    $flag = true;
                    break;
                }
            }
            if (!$flag) {
                return error('参数错误：错误的product_id');
            }
        }
        $product_info = Db::name('product')->field('id,name,pic')->find($product_id);
        $data['product_info'] = $product_info;
        $shopkeeper_info = Db::name('user')->field('id,name,avatar')->find($user_id);
        $data['shopkeeper'] = $shopkeeper_info;
        $data['tags'] = config('tags');

        return success($data);
    }

    // 评价
    public function evaluate()
    {
        $order_id = input('post.order_id', '');
        if (!$order_id || 24 != strlen($order_id)) {
            return error('参数错误：错误的order_id');
        }
        $order_info = Db::name('order')->find($order_id);
        if (!$order_info) {
            return error('未找到该订单');
        }
        $user_info = session('user_info');
        if ($order_info['buyer'] != $user_info['id']) {
            return error('这不是您的订单，不能评价');
        }
        if (12 != $order_info['status']) {
            return error('订单不处于待评价状态');
        }
        $product_id = input('post.product_id', '');
        $specifications = '';
        if (!$product_id && count($order_info['product']) > 1) {
            return error('参数错误：错误的product_id');
        }
        if (!$product_id && 1 == count($order_info['product'])) {
            $product_id = $order_info['product'][0]['product_id'];
            $specifications = $order_info['product'][0]['specifications'];
        } else {
            $flag = false;
            foreach ($order_info['product'] as $key => $value) {
                if ($product_id == $value['product_id']) {
                    $specifications = $value['specifications'];
                    $flag = true;
                    break;
                }
            }
            if (!$flag) {
                return error('参数错误：错误的product_id');
            }
        }
        $row = input('post.', []);
        //产品评价
        $data = ['ct' => time()];
        $data['score'] = intval($row['score']);
        if (0 == $data['score']) {
            return error('请选择评分');
        }
        if ($data['score'] < 0 || $data['score'] > 5) {
            return error('请选正确的择评分');
        }
        $data['content'] = strval($row['content']);
        if (0 == strlen($data['content'])) {
            // return error('请填写内容');
            $data['content'] = '默认好评';
        }
        if ($row['pics']) {
            $data['pics'] = $row['pics'];
        }
        //店主评价 只有标签 （小于100是好评 大于等于100差评）
        if ($row['tags'] && is_array($row['tags'])) {
            $tags = [];
            $praise = $not_praise = 0;
            foreach ($row['tags'] as $key => $value) {
                $v = intval($value);
                if ($v < 100) {
                    ++$praise;
                } else {
                    ++$not_praise;
                }
                $tags[] = $v;
            }
            //既有差评又有好评的驳回(可以好坏一起评价)
            // if ($praise != count($row['tags']) && $not_praise != count($row['tags'])) {
            //     return error('你选的标签既有好评又有差评，请重新填写');
            // }
            $data['tags'] = $tags;
            $data['praise'] = $praise;
            $data['not_praise'] = $not_praise;
        } else {
            //默认好评
            $data['praise'] = 1;
            $data['not_praise'] = 0;
        }
        $data['anonymous'] = $row['anonymous'] ? 1 : 0;
        $data['seller'] = $order_info['seller'];
        $data['buyer'] = $order_info['buyer'];
        $data['product_id'] = $product_id;
        $data['order_id'] = $order_id;
        $data['specifications'] = $specifications;
        Db::name('evaluate')->insert($data);
        // 修改小店综合评分
        $shop_info = Db::name('shop')->where(['user_id' => $order_info['seller']])->find();
        $shop_info['score'] = ($shop_info['score'] * $shop_info['evaluate_num'] + $data['score']) / ($shop_info['evaluate_num'] + 1);
        foreach ($tags as   $v) {
            $flag = false;
            foreach ($shop_info['tags'] as $key => $value) {
                if ($v == $key) {
                    ++$shop_info['tags'][$key];
                    $flag = true;
                    break;
                }
            }
            if (!$flag) {
                $shop_info['tags'][$v] = 1;
            }
        }
        Db::name('shop')->where(['user_id' => $order_info['seller']])->update(['score' => $shop_info['score'], 'evaluate_num' => $shop_info['evaluate_num'] + 1, 'sales' => $shop_info['sales'] + 1, 'tags' => $shop_info['tags']]);
        // 全部评价后订单改为交易完成状态
        $flag = 0;
        foreach ($order_info['product'] as $key => $value) {
            if ($product_id == $value['product_id']) {
                $value['evaluate'] = 1;
                $order_info['product'][$key]['evaluate'] = 1;
                $order_info['product'][$key]['evaluate_time'] = time();
            }
            if ($value['evaluate']) {
                ++$flag;
            }
        }
        $update_row = ['product' => $order_info['product']];
        if ($flag == count($order_info['product'])) {
            $update_row['status'] = 10;
            $update_row['evaluate_time'] = time();
        }
        Db::name('order')->where('id', $order_id)->update($update_row);

        return success();
    }
}
